<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    pageContext.setAttribute("contextPath", request.getContextPath());
%>
<html>
<head>
    <title>员工列表页面</title>

    <%--百度 CDN--%>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

    <!-- 可选的 Bootstrap 主题文件（一般不用引入） -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css" integrity="sha384-6pzBo3FDv/PJ8r2KRkGHifhEocL+1X2rVCTTkUfGk7/0pbek5mMa1upzvWbrUbOZ" crossorigin="anonymous">

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>

    <script type="text/javascript">
        /*定义总记录数和当前页变量*/
        let totalRecord, pageNum;

        $(function () {
            // 进入员工页面默认显示第一页数据
            gotoPage(1);

            /*点击添加员工按钮触发模态框*/
            $("#addEmployeeBtn").click(function () {
                // 触发模态框之前重置表单并清空模态框内内容
                resetForm("#addEmployeeModal form");
                // 触发模态框前加载部门信息
                loadDepartments("#addEmployeeModal select");
                // 触发模态框
                $("#addEmployeeModal").modal();
            })

            /*校验员工姓名是否重复*/
            $("#empName").change(function () {
                // 获取用户名输入框的内容
                let empNameVal = $(this).val();
                $.ajax({
                    url: "${contextPath}/checkEmpName",
                    type: "GET",
                    data: {empName: empNameVal},
                    success: function (result) {
                        if (result.code === 100) {
                            verifyHintMessage("success", "#empName", "员工姓名可用！");
                            $("#saveEmployeeBtn").attr("checkName", "success");
                        } else {
                            verifyHintMessage("error", "#empName", result.extend.hintMessage);
                            $("#saveEmployeeBtn").attr("checkName", "error");
                        }
                    }
                })
            })

            /*添加并保存员工*/
            $("#saveEmployeeBtn").click(function () {

                // 当员工用户名存在时，点击保存按钮返回false
                if ($(this).attr("checkName") === "error") {
                    return false;
                }

                /*检验用户名合理性*/
                let empNameVal = $("#empName").val();
                let empNameRegExp = /(^[a-zA-Z][a-zA-Z0-9_]{4,14}$)|(^[\u4e00-\u9fa5_a-zA-Z0-9_]{2,5}$)/;
                if (!empNameRegExp.test(empNameVal)) {
                    verifyHintMessage("error", "#empName", "请按要求【英文5-15位，中文2-5位】输入！");
                    return false;
                } else {
                    verifyHintMessage("success", "#empName", "");
                }

                /*校验邮箱合理性*/
                let mailboxVal = $("#mailbox").val();
                let mailboxRegExp = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
                if (!mailboxRegExp.test(mailboxVal)) {
                    verifyHintMessage("error", "#mailbox", "邮箱格式不正确！");
                    return false;
                } else {
                    verifyHintMessage("success", "#mailbox", "")
                }

                let formData = $("#addEmployeeModal form").serialize();
                $.ajax({
                    url: "${contextPath}/addEmployee",
                    type: "POST",
                    data: formData,
                    dataType: "json",
                    success: function (result) {
                        if (result.code === 100) {
                            // 关闭模态框
                            $("#addEmployeeModal").modal('hide');
                            // 跳转至最后一页
                            gotoPage(totalRecord);
                        } else {
                            // 显示失败信息：有哪个字段就显示哪个字段
                            if (undefined !== result.extend.errorFields.empName) {
                                // 显示员工姓名错误信息
                                verifyHintMessage("error", "#empName", result.extend.errorFields.empName);
                            }
                            if (undefined !== result.extend.errorFields.mailbox) {
                                // 显示邮箱错误信息
                                verifyHintMessage("error", "#mailbox", result.extend.errorFields.mailbox)
                            }
                        }

                    }
                })
            })

            /*点击编辑员工按钮触发模态框(由于加载完元素后才添加事件，导致事件不能正常触发，所以使用on函数解决)*/
            $(document).on("click", ".updateBtn", function () {
                // 1、触发模态框前加载部门信息
                loadDepartments("#updateEmployeeModal select");
                // 2、查出员工信息并显示
                findEmployeeById($(this).attr("updateEmpId"));
                // 3、把员工id传给修改模态框的更新按钮
                $("#updateEmployeeBtn").attr("updateEmpId", $(this).attr("updateEmpId"));
                // 4、触发模态框
                $("#updateEmployeeModal").modal();
            })

            /*修改并更新员工*/
            $("#updateEmployeeBtn").click(function () {
                // 1、校验邮箱合理性
                let mailboxVal = $("#updateMailbox").val();
                let mailboxRegExp = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
                if (!mailboxRegExp.test(mailboxVal)) {
                    verifyHintMessage("error", "#updateMailbox", "邮箱格式不正确！");
                    return false;
                } else {
                    verifyHintMessage("success", "#updateMailbox", "")
                }

                // 2、发送Ajax请求给服务器修改员工数据
                $.ajax({
                    url: "${contextPath}/updateEmployee/" + $(this).attr("updateEmpId"),
                    type: "PUT",
                    data: $("#updateEmployeeModal form").serialize(),
                    success: function (result) {
                        alert(result.message);
                        // 关闭模态框
                        $("#updateEmployeeModal").modal("hide");
                        // 跳转回修改员工数据的页面
                        gotoPage(pageNum);
                    }
                })
            })

            /*删除员工*/
            $(document).on("click", ".deleteBtn", function () {
                // 获取当前员工的id及姓名
                let empName = $(this).parents("tr").find("td:eq(2)").text();
                let empId = $(this).attr("deleteBtnId");
                // 弹出删除员工确认框
                if (confirm("确定删除【" + empName + "】吗？")) {
                    $.ajax({
                        url: "${contextPath}/delete/" + empId,
                        type: "DELETE",
                        success: function (result) {
                            alert(result.message);
                            gotoPage(pageNum);
                        }
                    })
                }
            })

            /*单选按钮的全选*/
            $("#checkAll").click(function () {
                // 使用prop()读取DOM原生属性的值，点击按钮进行全选操作
                $(".checkItem").prop("checked", $(this).prop("checked"));
            })

            /*单选按钮的反选*/
            $(document).on("click", ".checkItem", function () {
                // 判断当前选中的按钮与总按钮个数是否相等
                let flag = $(".checkItem:checked").length === $(".checkItem").length;
                // 相等为true则选中，否则为不选中状态
                $("#checkAll").prop("checked", flag);
            })

            /*批量删除员工*/
            $("#delEmployeeBtn").click(function () {
                let employeesId = "";
                let employeesName = "";
                // 循环拿到每一个按钮选中数据的id和名字并进行拼接
                $.each($(".checkItem:checked"), function () {
                    employeesId += $(this).parents("tr").find("td:eq(1)").text() + "-";
                    employeesName += $(this).parents("tr").find("td:eq(2)").text() + "，";
                })
                // 去除末尾多余的拼接符号
                employeesId = employeesId.substring(0, employeesId.length - 1);
                employeesName = employeesName.substring(0, employeesName.length - 1);
                if (confirm("确定删除【" + employeesName + "】们吗？")) {
                    $.ajax({
                        url: "${contextPath}/delete/" + employeesId,
                        type: "DELETE",
                        success: function (result) {
                            alert(result.message);
                            gotoPage(pageNum);
                        }
                    })
                }
            })

        })

        /*跳转请求页面*/
        function gotoPage(pageNum) {
            $.ajax({
                url: "${contextPath}/employees",
                data: {pageNum: pageNum},
                type: "get",
                dataType: "json",
                success: function (result) {
                    buid_emps_table(result);
                    buid_page_info(result);
                    buid_page_nav(result);
                }
            })
        }

        /*解析并显示员工数据*/
        function buid_emps_table(result) {
            // 由于Ajax异步刷新页面，查询后的旧数据仍滞留在页面，所以发送新请求后清空原数据
            $("#empsTable tbody").empty();
            let emps = result.extend.pageInfo.list;
            $.each(emps, function (index, item) {
                let checkItem = $("<td><input type='checkbox' class='checkItem'></td>");
                let empId = $("<td></td>").append(item.empId);
                let empName = $("<td></td>").append(item.empName);
                let gender = $("<td></td>").append(item.gender === 'M' ? "男" : "女");
                let mailbox = $("<td></td>").append(item.mailbox);
                let deptName = $("<td></td>").append(item.department.deptName);
                let editBtn = $("<button type='button'></button>").addClass("btn btn-info btn-sm updateBtn")
                    .append("<span></span>").addClass("glyphicon glyphicon-pencil").append("编辑");
                // 为编辑按钮添加一个自定义属性，表示当前员工id值
                editBtn.attr("updateEmpId", item.empId);
                let deleBtn = $("<button type='button'></button>").addClass("btn btn-danger btn-sm deleteBtn")
                    .append("<span></span>").addClass("glyphicon glyphicon-trash").append("删除");
                let tdBtn = $("<td></td>").append(editBtn).append(" ").append(deleBtn);
                // 为删除按钮添加一个自定义属性，表示当前员工id值
                deleBtn.attr("deleteBtnId", item.empId);
                /*链式编程：append方法执行完成后仍是返回原来的元素*/
                $("<tr></tr>").append(checkItem).append(empId).append(empName).append(gender).append(mailbox).append(deptName)
                    .append(tdBtn).appendTo("#empsTable tbody");
            })
        }

        /*解析并显示分页信息*/
        function buid_page_info(result) {
            totalRecord = result.extend.pageInfo.total;
            // 由于Ajax异步刷新页面，查询后的旧数据仍滞留在页面，所以发送新请求后清空原数据
            $("#pageInfo").empty().append("当前第" + result.extend.pageInfo.pageNum + "页，共有" + result.extend.pageInfo.pages + "页，总计" + result.extend.pageInfo.total + "条记录");
            // 全局变量获取到当前页码
            pageNum = result.extend.pageInfo.pageNum;
        }

        /*解析并显示分页导航条信息*/
        function buid_page_nav(result) {
            // 由于Ajax异步刷新页面，查询后的旧数据仍滞留在页面，所以发送新请求后清空原数据
            $("#pageNav").empty();

            let pagination = $("<ul></ul>").addClass("pagination");

            let firstPage = $("<li></li>").append($("<a></a>").attr("href", "#").append("首页"));
            let previousPage = $("<li></li>").append($("<a></a>").attr("href", "#").append($("<span></span>").append("&laquo;")));

            // 如果当前页不存在上一页的情况下将首页和上一页按钮禁用
            if (result.extend.pageInfo.hasPreviousPage === false) {
                firstPage.addClass("disabled");
                previousPage.addClass("disabled");
            } else {
                // 首页和上一页进行跳转
                firstPage.click(function () {
                    gotoPage(1);
                })

                previousPage.click(function () {
                    gotoPage(result.extend.pageInfo.pageNum - 1);
                })
            }

            // 将首页和上一页添加至ul中
            pagination.append(firstPage).append(previousPage);

            $.each(result.extend.pageInfo.navigatepageNums, function (index, item) {
                let navigatepageNum = $("<li></li>").append($("<a></a>").attr("href", "#").append(item));
                if (result.extend.pageInfo.pageNum === item) {
                    // 如果当前页与遍历显示的页数相同，为按钮添加激活状态
                    navigatepageNum.addClass("active");
                }
                // 点击页面按钮进行跳转
                navigatepageNum.click(function () {
                    gotoPage(item);
                })
                // 将遍历出的导航页码添加至ul中
                pagination.append(navigatepageNum);
            })

            let nextPage = $("<li></li>").append($("<a></a>").attr("href", "#").append($("<span></span>").append("&raquo;")));
            let lastPage = $("<li></li>").append($("<a></a>").attr("href", "#").append("末页"));

            // 如果当前页不存在下一页的情况下将末页和下一页按钮禁用
            if (result.extend.pageInfo.hasNextPage === false) {
                nextPage.addClass("disabled");
                lastPage.addClass("disabled");
            } else {
                // 末页和下一页进行跳转
                nextPage.click(function () {
                    gotoPage(result.extend.pageInfo.pageNum + 1);
                })

                lastPage.click(function () {
                    gotoPage(result.extend.pageInfo.pages);
                })
            }

            // 将下一页和末页添加至ul中
            pagination.append(nextPage).append(lastPage);
            /*将ul添加至nav中*/
            let navElement = $("<nav></nav>").append(pagination);
            // 将导航条添加至栅格列中
            navElement.appendTo("#pageNav");
        }

        /*加载部门信息*/
        function loadDepartments(element) {
            // 每次加载部门信息清空下拉列表中的所有选项
            $(element).empty();
            $.ajax({
                url: "${contextPath}/departments",
                type: "get",
                success: function (result) {
                    $.each(result.extend.departmentList, function () {
                        $(element).append($("<option></option>").attr("value", this.deptId).append(this.deptName));
                    })
                }
            })
        }

        /*校验信息*/
        function verifyHintMessage(status, element, message) {
            $(element).parent().removeClass("has-error has-success");
            $(element).next("span").text("");

            if (status === "error") {
                $(element).parent().addClass("has-error");
                $(element).next("span").text(message);
            } else if (status === "success") {
                $(element).parent().addClass("has-success");
                $(element).next("span").text(message);
            }
        }

        /*清空表单样式及内容*/
        function resetForm(element) {
            // 重置表单
            $(element)[0].reset();

            // 移除输入框颜色变化样式
            $(element).find("*").removeClass("has-success has-error");
            // 清空提示信息
            $(element).find(".help-block").text("");
        }

        /*通过主键id获取员工信息*/
        function findEmployeeById(id) {
            $.ajax({
                url: "${contextPath}/findEmployeeById/" + id,
                type: "GET",
                success: function (result) {
                    let employeeData = result.extend.employee;
                    $("#updateEmpNameStatic").text(employeeData.empName);
                    $("#updateMailbox").val(employeeData.mailbox);
                    $("#updateEmployeeModal input[name=gender]").val([employeeData.gender]);
                    $("#updateEmployeeModal select").val([employeeData.deptId]);
                }
            })
        }
    </script>
</head>
<body>

<div class="container">
    <%--标题--%>
    <div class="row">
        <div class="col-md-12">
            <h1>SSM-CRUD</h1>
        </div>
    </div>
    <%--按钮--%>
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
            <!-- Button trigger modal -->
            <button type="button" id="addEmployeeBtn" class="btn btn-primary" data-toggle="modal"
                    data-target="addEmployeeModal">新增
            </button>
            <button type="button" id="delEmployeeBtn" class="btn btn-danger">删除</button>
        </div>
    </div>
    <%--表格数据--%>
    <div class="row">
        <div class="col-md-12">
            <table id="empsTable" class="table table-striped table-hover">
                <thead>
                <tr>
                    <th><label for="checkAll"></label><input type="checkbox" id="checkAll"></th>
                    <th>ID</th>
                    <th>EmpName</th>
                    <th>Gender</th>
                    <th>MailBox</th>
                    <th>DeptName</th>
                    <th>Operation</th>
                </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>
    <%--分页信息--%>
    <div class="row">
        <div id="pageInfo" class="col-md-6"></div>
        <%--分页导航条--%>
        <div id="pageNav" class="col-md-6"></div>
    </div>
</div>

<!-- Add Employee Modal -->
<div class="modal fade" id="addEmployeeModal" tabindex="-1" role="dialog" aria-labelledby="addEmployeeModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="addEmployeeModalLabel">添加员工信息</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label for="empName" class="col-sm-2 control-label">EmpName</label>
                        <div class="col-sm-10">
                            <input type="text" name="empName" class="form-control" id="empName" placeholder="EmpName">
                            <span class="help-block"></span>
                        </div>

                    </div>
                    <div class="form-group">
                        <label for="mailbox" class="col-sm-2 control-label">Mailbox</label>
                        <div class="col-sm-10">
                            <input type="email" name="mailbox" class="form-control" id="mailbox"
                                   placeholder="Mailbox@163.com">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="empName" class="col-sm-2 control-label">Gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="male" value="M" checked="checked"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="female" value="F"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="deptId" class="col-sm-2 control-label">deptName</label>
                        <div class="col-sm-10">
                            <select class="form-control" id="deptId" name="deptId"></select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="saveEmployeeBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- Update Employee Modal -->
<div class="modal fade" id="updateEmployeeModal" tabindex="-1" role="dialog" aria-labelledby="updateEmployeeModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="updateEmployeeModalLabel">修改员工信息</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label for="empName" class="col-sm-2 control-label">EmpName</label>
                        <div class="col-sm-10">
                            <p class="form-control-static" name="empName" id="updateEmpNameStatic"></p>
                            <span class="help-block"></span>
                        </div>

                    </div>
                    <div class="form-group">
                        <label for="mailbox" class="col-sm-2 control-label">Mailbox</label>
                        <div class="col-sm-10">
                            <input type="email" name="mailbox" class="form-control" id="updateMailbox"
                                   placeholder="Mailbox@163.com">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="empName" class="col-sm-2 control-label">Gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="updateMale" value="M" checked="checked"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="updateFemale" value="F"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="updateDeptId" class="col-sm-2 control-label">deptName</label>
                        <div class="col-sm-10">
                            <select class="form-control" id="updateDeptId" name="deptId"></select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="updateEmployeeBtn">更新</button>
            </div>
        </div>
    </div>
</div>
</body>
</html>